package com.diaohw.platform.framework.web.advice;

import com.diaohw.platform.common.obj.Result;
import com.diaohw.platform.common.util.JsonUtil;
import com.diaohw.platform.framework.web.IgnoredResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import static com.diaohw.platform.common.obj.thread.RequestThread.putResponseData;


@Component
@RestControllerAdvice(basePackages = "com.diaohw")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@Nullable MethodParameter returnType, @Nullable Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, @Nullable MethodParameter returnType, @Nullable MediaType selectedContentType, @Nullable Class<? extends HttpMessageConverter<?>> selectedConverterType, @Nullable ServerHttpRequest request, @Nullable ServerHttpResponse response) {

        assert returnType != null;
        if (void.class.equals(returnType.getParameterType())) {
            putResponseData(Result.success(body));
            return body;
        }
        if (returnType.getMethod() != null && returnType.getMethod().isAnnotationPresent(IgnoredResponse.class)) {
            putResponseData(Result.success(body));
            return body;
        }

        if (body instanceof Result<?> result) {
            putResponseData(result);
            return body;
        }
        final Result<Object> result = Result.success(body);
        putResponseData(result);
        if (String.class.equals(returnType.getParameterType())) {
            return JsonUtil.toJsonString(result);
        }
        return result;
    }


}
